#include <webx/route.h>
#include <dbentity/T_XG_MENU.h>

class GetMenuList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetMenuList)

int GetMenuList::process()
{
	param_int(level);
	param_string(folder);
	
	checkLogin();

	string sqlcmd;
	sp<RowData> row;
	sp<QueryResult> rs;
	int res = XG_SYSERR;
	sp<DBConnect> dbconn = webx::GetDBConnect();

	if (folder.empty())
	{
		if (level == 1)
		{
			sqlcmd = "SELECT ID,URL,ICON,TITLE,FOLDER,ENABLED,POSITION,STATETIME FROM T_XG_MENU WHERE (TITLE IS NULL OR TITLE='') ORDER BY POSITION ASC";
		}
		else if (level == 2)
		{
			sqlcmd = "SELECT ID,URL,ICON,TITLE,FOLDER,ENABLED,POSITION,STATETIME FROM T_XG_MENU WHERE TITLE NOT NULL AND TITLE<>'' ORDER BY POSITION ASC";
		}
		else
		{
			sqlcmd = "SELECT ID,URL,ICON,TITLE,FOLDER,ENABLED,POSITION,STATETIME FROM T_XG_MENU WHERE ENABLED>0 ORDER BY FOLDER ASC,TITLE ASC";
		}

		rs = dbconn->query(sqlcmd);
	}
	else
	{
		sqlcmd = "SELECT ID,URL,ICON,TITLE,FOLDER,ENABLED,POSITION,STATETIME FROM T_XG_MENU WHERE FOLDER=? AND ENABLED>0 ORDER BY POSITION ASC";

		rs = dbconn->query(sqlcmd, folder);
	}

	if (rs)
	{
		res = 0;

		JsonElement arr = json.addArray("list");
		
		while (row = rs->next())
		{
			if (folder.length() > 0 && row->getString(3).empty())
			{
				json["enabled"] = row->getString(5);

				continue;
			}

			JsonElement item = arr[res++];

			item["id"] = row->getString(0);
			item["url"] = row->getString(1);
			item["icon"] = row->getString(2);
			item["title"] = row->getString(3);
			item["folder"] = row->getString(4);
			item["enabled"] = row->getString(5);
			item["position"] = row->getString(6);
			item["statetime"] = row->getString(7);
		}
	}

	json["code"] = res;
	out << json;
	
	return XG_OK;
}